package org.qy.star_server.controller;

import lombok.extern.slf4j.Slf4j;
import org.qy.star_common.message.Message;
import org.qy.star_server.core.BrokerServer;
import org.qy.star_server.core.User;
import org.qy.star_server.data.center.DiskDataCenter;
import org.qy.star_server.data.center.MemoryDataCenter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author yinger
 * @description TODO
 * @date 2024/3/31 16:09
 **/
@RequestMapping("/message")
@RestController
@Slf4j
public class MessageController {
    private final MemoryDataCenter memory = BrokerServer.memory;

    @RequestMapping("/publish")
    public boolean publishMessage(String username,String virtualHostName, String exchangeName, Message message) {
        System.out.println("publish message:" + message);
        boolean result = false;
        try {
            User user =  memory.selectUser(username);
            // 将消息中的body转为byte[]
            message.setBody(message.getMessage().getBytes());
            message = Message.createMessageWithId(message.getMessageProperties(), message.getBody(), message.getRoutingKey());
            result = user.basicPublish(virtualHostName, exchangeName, message.getRoutingKey(), message.getMessageId(),message.getDeliveryMode(), message.getBody()).isEmpty();
        } catch (Exception e) {
            log.error("发布消息失败", e);
            return false;
        }
        return result;
    }
}
